package com.tjl.print_ji_ou;

import org.w3c.dom.ls.LSOutput;

import java.util.concurrent.locks.ReentrantLock;

public class Test {

    public static void main(String[] args) {
        System.out.println("程序开始");
        Printjo printjo = new Printjo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {//死循环
                    printjo.printJ();
                }
            }
        }, "奇数线程").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {//死循环
                    printjo.printO();
                }
            }
        }, "偶数线程").start();
    }
}


class Printjo {
    private boolean isPrintJO = false;
    private int max = 100;
    private int i = 1;
    ReentrantLock lock = new ReentrantLock();

    public synchronized void printJ() {
        try {

            if (!isPrintJO && i % 2 == 1 && i <= max) {
                //满足条件
                System.out.println(Thread.currentThread().getName() + "打印奇数：" + i);
                isPrintJO = true;
                i++;
                Thread.sleep(100);
                this.notifyAll();
                this.wait();

            } else {//不满足条件，叫人，等待
                this.notifyAll();
                this.wait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized void printO() {
        try {

            if (isPrintJO && i % 2 == 0 && i <= max) {
                System.out.println(Thread.currentThread().getName() + "打印偶数：" + i);
                isPrintJO = false;
                i++;
                Thread.sleep(100);
                this.notifyAll();
                this.wait();

            } else {
                this.notifyAll();
                this.wait();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}